package app.Disthanitian.thaistyle.EmerMez;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class AddContactView extends Activity {
    String displayName = "", emailAddress="", phoneNumber="";
    Uri uriPhoto;
    Bitmap bitmap;
	Button AddContact;
	ListView listView;
	ArrayList values;
	//ArrayAdapter adapter;
	public static String result = "";
	private ContactAdapter adapter;
	List<MemberContact> listPersons ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//listView = (ListView) View.inflate(this, R.layout.addcontact, null);
		//setContentView(listView);
		setContentView(R.layout.addcontact);
	    listView = (ListView) findViewById(R.id.contactList);
	}

	// Action Menu Bar (Plus BTN)
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.contacts, menu);

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_addcontact:
			CallContact();
		}
		return super.onOptionsItemSelected(item);
	}

	private void CallContact() {
		//Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
		//intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
		//startActivityForResult(intent, 1);

		Intent intent1=new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
		startActivityForResult(intent1,100);
		
	}

	
	   @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		   String displayName = "", emailAddress="", phoneNumber="";
               Uri uri;
                // Uri a= ContactsContract.Contacts.CONTENT_URI;
               String id = null;
               if (data != null) {
            	   
                        uri = data.getData();
                               
                      ContentResolver cr = getContentResolver();
                       Cursor cur = cr.query(uri,null, null, null, null);
                       if (cur.getCount() > 0) {
                           while (cur.moveToNext()) {
                                id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                               displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                               
                               Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                                                         ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ? ", new String[]{id}, null); 
                                       while (emailCur.moveToNext()) { 
                                           // This would allow you get several email addresses
                                           // if the email addresses were stored in an array
                                           emailAddress = emailCur.getString( emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                                           String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 
                                       } 
                                       emailCur.close();
                               
                               if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                                   //Query phone here.  Covered next
                                        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                                                   new String[]{id}, null);
                                               while (pCur.moveToNext()) {
                                                   // Do something with phones
                                                       
                                                        phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                               } 
                                               pCur.close();
                               }
                               
                           }
                          
                       }
                       // GET Photo
                       Long idphoto = Long.parseLong(id);
                       byte[] data1 = null;
                       Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idphoto);
                       Uri photoUri=Uri.withAppendedPath(person,ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
                     
                       
                       Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
                       InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),my_contact_Uri);            
                       BufferedInputStream buf =new BufferedInputStream(photo_stream);
                       Bitmap my_btmp = BitmapFactory.decodeStream(buf);
                         // profile.setImageBitmap(my_btmp);      
                       
                       /*  Cursor cursor = getContentResolver().query(photoUri, new String[] {Contacts.Photo.PHOTO}, null, null, null);
                    	    
                    	     try {
                    	         if (cursor.moveToFirst()) {
                    	              data1 = cursor.getBlob(0);
                    	             if (data1 != null) {
                    	                  new ByteArrayInputStream(data1);
                    	                
                    	             }
                    	         }
                    	     } finally {
                    	         cursor.close();
                    	     }
                    	    
                       
                       //-----------
                       */
                       Toast.makeText(AddContactView.this,"\n"+uri+ "\n" +"Email:" + emailAddress +"\n"+"Name:" +displayName +"\n"+"Number:"+  phoneNumber,
                                               Toast.LENGTH_LONG).show();
                       showSelectedNumber(phoneNumber,emailAddress,displayName,photoUri);
                       //showSelectedNumber(phoneNumber,emailAddress,displayName,my_btmp);
               }
       }
       
	
	public void showSelectedNumber(String number, String email, String name, Uri uri) {//Bitmap my_btmp
		
		 displayName = name;
		 emailAddress=email;
	     phoneNumber=number;
	     uriPhoto =uri;
	     //bitmap =my_btmp;
	 	//Toast.makeText(getApplicationContext(),bitmap.toString(),Toast.LENGTH_LONG).show();
		//values = new ArrayList();

		//values.add("Name:" + name + "\n Phone:" + number + "\n Email:" + email);
		//values.add(byteArrayInputStream);
		//values.add(uri);

		//adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,android.R.id.text1, values);

		// Assign adapter to ListView
		//listView.setAdapter(adapter);
		//adapter.notifyDataSetChanged();

		// }
		
		
//		adapter = new ContactAdapter(this, R.layout.listview_item_rows, loadPersons());
		listView.setAdapter(adapter);

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> a, View v,int position, long id) {

				Toast.makeText(getApplicationContext(), "Delete " + position,Toast.LENGTH_LONG).show();
				listPersons.remove(position);
				adapter.notifyDataSetChanged();
				adapter.notifyDataSetInvalidated();
				return true;
			}

		}); 
		
	

	}

	private List<MemberContact> loadPersons() {
		 listPersons = new ArrayList<MemberContact>(100);
	//	for (int i = 0; i < 100; i++) {
	   // listPersons.add(new MemberContact(displayName,emailAddress, phoneNumber, R.drawable.degaulle));
		listPersons.add(new MemberContact(displayName,emailAddress, phoneNumber, uriPhoto));
	//	listPersons.add(new MemberContact(displayName,emailAddress, phoneNumber, bitmap));
	//	}
		return listPersons;
	}



}
